package com.yonyou.crm.base.doc.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.doc.entity.BaseDocDetailVO;
import com.yonyou.crm.base.doc.entity.BaseDocVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class BaseDocBizServiceImpl extends BaseBizServiceImpl<BaseDocVO> {
	
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private BaseDocDetailBizServiceImpl detailBizService;
	
	public Page<BaseDocVO> getPage(Page<BaseDocVO> page, Map<String, Object> paramMap){
		Page<BaseDocVO> baseDocPage = null;
		if (paramMap == null) {
			paramMap = new HashMap<String, Object>();
		}
		paramMap.put("tenantId", InvocationInfoProxy.getTenantid());
		baseDocPage = super.pageSelect(BaseDocVO.class, page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		transBaseDoc(baseDocPage.getData());
		return baseDocPage;
	}
	
	private List<BaseDocVO> transBaseDoc(List<BaseDocVO> baseDocList){
		if(baseDocList != null && baseDocList.size() > 0) {
			List<FieldRelation<BaseDocVO>> relations = new ArrayList<FieldRelation<BaseDocVO>>();
			relations.add(new EnumFieldRelation<BaseDocVO>(BaseDocVO.class, "enableState", "enableStateName", enumService, "enable_state"));
			relations.add(new EnumFieldRelation<BaseDocVO>(BaseDocVO.class, "isDefault", "isDefaultName", enumService, "whether"));
			new FieldRelationHandler<BaseDocVO>().handler(baseDocList, relations);
		}
		return baseDocList;
	}
	
	private List<BaseDocDetailVO> transBaseDocDetail(List<BaseDocDetailVO> baseDocDetailList){
		if(baseDocDetailList != null && baseDocDetailList.size() > 0) {
			List<FieldRelation<BaseDocDetailVO>> relations = new ArrayList<FieldRelation<BaseDocDetailVO>>();
			relations.add(new EnumFieldRelation<BaseDocDetailVO>(BaseDocDetailVO.class, "enableState", "enableStateName", enumService, "enable_state"));
			new FieldRelationHandler<BaseDocDetailVO>().handler(baseDocDetailList, relations);
		}
		return baseDocDetailList;
	}
	
	public BaseDocVO save(BaseDocVO vo){
		//获取档案明细信息，保存子表信息
		BaseDocVO baseDoc = super.saveVO(vo);
		Long id = baseDoc.getId();
		List<BaseDocDetailVO> baseDocDetailList = vo.getBaseDocDetailList();
		if (baseDocDetailList != null && baseDocDetailList.size() > 0) {
			for (BaseDocDetailVO bvo : baseDocDetailList) {
				bvo.setBaseDocId(id);
			}
			// 批量保存档案明细表体信息
			detailBizService.batchInsertBaseDocDetail(baseDocDetailList);
		}
		return baseDoc;
	}
	
	public int deletebaseDocByIDs(String[] idStrs) {
		dao.batchDelete(BaseDocDetailVO.class, idStrs);
		detailBizService.deletebaseDocDetailBybaseDocIds(idStrs);
		return super.batchDeleteByIDs(BaseDocVO.class, idStrs);
	}
	
	public BaseDocVO updatebaseDoc(BaseDocVO baseDoc){
		BaseDocVO baseDocVO = super.updateVO(baseDoc);
		handlebaseDoc(baseDoc);
		return baseDocVO;
	}
	
	private void handlebaseDoc(BaseDocVO baseDoc){
		List<BaseDocDetailVO> baseDocDetailList = baseDoc.getBaseDocDetailList();
        List<BaseDocDetailVO> addList = new ArrayList<BaseDocDetailVO>();
        List<BaseDocDetailVO> updateList = new ArrayList<BaseDocDetailVO>();
        List<BaseDocDetailVO> deleteList = new ArrayList<BaseDocDetailVO>();
        for (BaseDocDetailVO bvo : baseDocDetailList) {
            String editState = bvo.getEditState();
            if ("add".equalsIgnoreCase(editState)) {
                bvo.setBaseDocId(baseDoc.getId());
                addList.add(bvo);
            } else if ("update".equalsIgnoreCase(editState)) {
            	bvo.setBaseDocId(baseDoc.getId());
                updateList.add(bvo);
            } else if ("delete".equalsIgnoreCase(editState)) {
            	bvo.setBaseDocId(baseDoc.getId());
                deleteList.add(bvo);
            }
        }
        if (addList.size() > 0) detailBizService.batchInsertBaseDocDetail(addList);

        if (updateList.size() > 0) detailBizService.batchUpdateBaseDocDetail(updateList);

        if (deleteList.size() > 0) {
            List<Long> deleteIdList = new ArrayList<Long>();
            for (BaseDocDetailVO bvo : deleteList) {
                deleteIdList.add(bvo.getId());
            }
            detailBizService.deleteBaseDocDetailByIds(deleteIdList.toArray());
        }
	}
	
	public BaseDocVO getbaseDocById(Long id){
		BaseDocVO baseDoc = super.getVOById(BaseDocVO.class, id);
		
		List<BaseDocDetailVO> baseDocDetailList = baseDoc.getBaseDocDetailList();
		if(baseDocDetailList != null && baseDocDetailList.size() > 0){
			transBaseDocDetail(baseDocDetailList);
		}
		List<BaseDocVO> baseDocList = new ArrayList<BaseDocVO>();
		baseDocList.add(baseDoc);
		transBaseDoc(baseDocList);
		baseDoc = baseDocList.get(0);
		return baseDoc;
	}
	
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(BaseDocVO.class, "selectFieldsByIds", para);
	}
	
	public Map<String, Object> getDocAndDetailList(Map<String, Object> idsMap){
		Map<String, Object> para = new HashMap<String, Object>();
		Object[] ids = idsMap.keySet().toArray();
		para.put("ids", ids);
		List<BaseDocVO> baseDocList = dao.selectVoList(BaseDocVO.class, "selectBaseDocList", para);
		Map<String, Object> baseDocMap=new HashMap<String, Object>();
		for(int i=0;i<baseDocList.size();i++){
			List<Map<String,String>> baseDocDetailList=new ArrayList<Map<String,String>>();
			List<BaseDocDetailVO> baseDocDetail = baseDocList.get(i).getBaseDocDetailList();
			for(int j=0;j<baseDocDetail.size();j++){
				Map<String,String> enumMap = new HashMap<String,String>();
				enumMap.put("key",baseDocDetail.get(j).getId().toString());
				enumMap.put("title",baseDocDetail.get(j).getName().toString());
				baseDocDetailList.add(enumMap);
			}
			String key = idsMap.get(baseDocList.get(i).getId().toString()).toString();
			if(key!=null&&!"".equals(key)){
				baseDocMap.put(key,baseDocDetailList);
			}
		}
		return baseDocMap;
	}

	/**
	 * 根据档案名称 和 租户id 返回档案子表信息
	 * @param docname
	 * @return
	 */
	public List<Map<String, Object>> getDocDetailListByDocname(String docname){
		Map<String,Object> param = new HashMap<>();
		param.put("docname",docname);
		param.put("tenant_id",new Long(InvocationInfoProxy.getTenantid()));
		List<Map<String, Object>> detailListMap = dao.selectList(BaseDocVO.class, "getDetailListByDocname", param);
		if(detailListMap.size() == 0) {//可能是预制档案 tenant_id = 0
			param.put("tenant_id", Long.valueOf("0"));
			detailListMap = dao.selectList(BaseDocVO.class, "getDetailListByDocname", param);
		}
		return detailListMap;
	}

	public List<BaseDocVO> getDocByIds(String[] ids){
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		List<BaseDocVO> baseDocList = dao.selectVoList(BaseDocVO.class, "selectBaseDocList", para);
		return baseDocList;
	}
}
